<?php

/**
 * User: zhangligang
 * Email: tzhang2450@163.com
 * Date: 2018/9/26
 * Time: 10:44
 */
namespace App\Console\Commands;

use App\Models\Apart;
use App\Models\Contract;
use App\Models\Program;
use Illuminate\Console\Command;

class TimerCommand extends Command
{
    /**
     * 命令行执行命令
     * @var string
     */
    protected $signature = 'timer';

    /**
     * 命令描述
     *
     * @var string
     */
    protected $description = 'timer in days or hours or minutes to check if any status will be changed';

    /**
     * Create a new command instance.
     *
     */
    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        function_exists('date_default_timezone_set');
        date_default_timezone_set('PRC');
        $now = time();
        if (in_array(get_date_hour(), [0, 8, 12, 18])) {
            $contracts = Contract::where('status', 1)->where('process', 3)->get();
            foreach ($contracts as $contract) {
                if (strtotime(local_date($contract->end_at, 'Y-m-d H:i:s')) < $now) {
                    $msg = ' contract [id:'.$contract->id.'] is over';
                    $contract->status = 2;
                    $contract->save();
                    $apart = Apart::where('id', $contract->apart_id)->first();
                    if ($apart) {
                        $apart->status = 2;
                        $apart->save();
                        $msg .= ' apart [id:'.$apart->id.'] is release';
                    }
                    Output::stdout(Output::COLOR_GREEN.$msg.Output::COLOR_NONE);
                    Tool::debug($msg);
                }
            }
        }
        $programs = Program::where('status', 1)->where('state', '>', 0)->get();
        foreach ($programs as $program) {
            $msg = '';
            if ($program->state == 1 && strtotime($program->apply_end_at) < $now) {
                $program->state = 2;
                $msg = ' program [id:'.$program->id.'] is now change to check';
            }
            if ($program->state == 2 && strtotime($program->check_end_at) < $now) {
                $program->state = 3;
                $msg = ' program [id:'.$program->id.'] is now change to confirm';
            }
            if (strtotime($program->end_at) < $now) {
                $program->status = 2;
                $msg = ' program [id:'.$program->id.'] is over';
            }
            if ($msg) {
                Output::stdout(Output::COLOR_GREEN.$msg.Output::COLOR_NONE);
                Tool::debug($msg);
                $program->save();
            }
        }
    }
}